﻿//C#编程实现遍历HashTable代码。 
//1）HashTable 存储的是无序的，也就是最先存储的键、值对不一定在第一个位置上；

//2）HashTable 存储的是弱类型的，也就是要由自己来控制存储类型，并且取值时要进行强制类型转换；

//这个要怪微软的方法描述不够清晰，要是清晰了直接就可以从描述中找到方法：

//先创建一个HashTable对象：

//System.Collections.HashTable ht=new System.Collections.HashTable();

//ht.Add("key_A","value_A");

//ht.Add("key_B","value_B");

//ht.Add("key_C","value_C");

//遍历方法一：

//System.Collections.IDictionaryEnumerator ht = ht.GetEnumerator();
//while (ht.MoveNext())
//{
//          ht.Key.ToString();//键

//    ht.Value.ToString();//值 

//          //这里已经取到当前的键、值对了，怎么输出和存储就看自己的了　　　　
//}

//遍历方法二：

//foreach (System.Collections.DictionaryEntry item in ht)
//{
//           item.Key.ToString();//键

//    item.Value.ToString();//值

//    //这里已经取到当前的键、值对了，怎么输出和存储就看自己的了　

//}



//本文来自: IT知道网(http://www.itwis.com) 详细出处参考：http://www.itwis.com/html/net/c/20110413/10189.html



//C#操作CMD命令行代码，public void CloseComputer(string cmd)
//{
//            Process p = new Process();
//            p.StartInfo.FileName = "cmd.exe";
//            p.StartInfo.UseShellExecute = false;
//            p.StartInfo.RedirectStandardInput = true;
//            p.StartInfo.RedirectStandardOutput = true;
//            p.StartInfo.RedirectStandardError = true;
//            p.StartInfo.CreateNoWindow = true;
//            p.Start();
//            //设置自动刷新缓冲并更新
//            p.StandardInput.AutoFlush = true;
//            //写入命令
//            p.StandardInput.WriteLine(cmd);
//            p.StandardInput.WriteLine("exit");
//            //等待结束
//            p.WaitForExit();
//            p.Close();
// }

//本文来自: IT知道网(http://www.itwis.com) 详细出处参考：http://www.itwis.com/html/net/c/20110413/10187.html


/*
常用正则表达式  
不包含字符串abc的正则表达式
 [^abc]表示不包含a、b、c中任意字符, 我想实现不包含字符串abc应该如何写表达式?
最简洁的写法：
\b((?!abc)\w)+\b
匹配由字母或数字或下划线或汉字组成的字串，但字串中不能出现abc
解释：
　　\b 匹配单词的开始或结束；
　　?!exp 零宽负向先行断言，只会匹配后缀exp不存在的位置；
　　\w 匹配字母或数字或下划线或汉字；
　　+ 重复一次或更多次；
　　\b((?!abc)\w)+\b 匹配由字母或数字或下划线或汉字组成的字串，但字串中不能出现abc。
测试：
　　http://www.regextester.com/
 * 
 * 
 * 
 * 
2009-11-23 09:09:56|  分类： 杂项 |字号 订阅
"^\d+$"　　//非负整数（正整数 + 0） 
"^[0-9]*[1-9][0-9]*$"　　//正整数 
"^((-\d+)|(0+))$"　　//非正整数（负整数 + 0） 
"^-[0-9]*[1-9][0-9]*$"　　//负整数 
"^-?\d+$"　　　　//整数 
"^\d+(\.\d+)?$"　　//非负浮点数（正浮点数 + 0） 
"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$"　　//正浮点数 
"^((-\d+(\.\d+)?)|(0+(\.0+)?))$"　　//非正浮点数（负浮点数 + 0） 
"^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$"　　//负浮点数 
"^(-?\d+)(\.\d+)?$"　　//浮点数 
"^[A-Za-z]+$"　　//由26个英文字母组成的字符串 
"^[A-Z]+$"　　//由26个英文字母的大写组成的字符串 
"^[a-z]+$"　　//由26个英文字母的小写组成的字符串 
"^[A-Za-z0-9]+$"　　//由数字和26个英文字母组成的字符串 
"^\w+$"　　//由数字、26个英文字母或者下划线组成的字符串 
"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"　　　　//email地址 
"^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$"　　//url
/^(d{2}|d{4})-((0([1-9]{1}))|(1[1|2]))-(([0-2]([1-9]{1}))|(3[0|1]))$/   //  年-月-日
/^((0([1-9]{1}))|(1[1|2]))/(([0-2]([1-9]{1}))|(3[0|1]))/(d{2}|d{4})$/   // 月/日/年
"^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$"   //Emil
/^((\+?[0-9]{2,4}\-[0-9]{3,4}\-)|([0-9]{3,4}\-))?([0-9]{7,8})(\-[0-9]+)?$/     //电话号码
"^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$"   //IP地址

匹配中文字符的正则表达式： [\u4e00-\u9fa5]
匹配双字节字符(包括汉字在内)：[^\x00-\xff]
匹配空行的正则表达式：\n[\s| ]*\r
匹配HTML标记的正则表达式：/<(.*)>.*<\/\1>|<(.*) \/>/
匹配首尾空格的正则表达式：(^\s*)|(\s*$)
匹配Email地址的正则表达式：\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
匹配网址URL的正则表达式：^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$
匹配帐号是否合法(字母开头，允许5-16字节，允许字母数字下划线)：^[a-zA-Z][a-zA-Z0-9_]{4,15}$
匹配国内电话号码：(\d{3}-|\d{4}-)?(\d{8}|\d{7})?
匹配腾讯QQ号：^[1-9]*[1-9][0-9]*$


元字符及其在正则表达式上下文中的行为： 

\ 将下一个字符标记为一个特殊字符、或一个原义字符、或一个后向引用、或一个八进制转义符。

^ 匹配输入字符串的开始位置。如果设置了 RegExp 对象的Multiline 属性，^ 也匹配 ’\n’ 或 ’\r’ 之后的位置。 

$ 匹配输入字符串的结束位置。如果设置了 RegExp 对象的Multiline 属性，$ 也匹配 ’\n’ 或 ’\r’ 之前的位置。 

* 匹配前面的子表达式零次或多次。 

+ 匹配前面的子表达式一次或多次。+ 等价于 {1,}。 

? 匹配前面的子表达式零次或一次。? 等价于 {0,1}。 

{n} n 是一个非负整数，匹配确定的n 次。

{n,} n 是一个非负整数，至少匹配n 次。 

{n,m} m 和 n 均为非负整数，其中n <= m。最少匹配 n 次且最多匹配 m 次。在逗号和两个数之间不能有空格。

? 当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时，匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串，而默认的贪婪模式则尽可能多的匹配所搜索的字符串。 

. 匹配除 "\n" 之外的任何单个字符。要匹配包括 ’\n’ 在内的任何字符，请使用象 ’[.\n]’ 的模式。 
(pattern) 匹配pattern 并获取这一匹配。 

(?:pattern) 匹配pattern 但不获取匹配结果，也就是说这是一个非获取匹配，不进行存储供以后使用。 

(?=pattern) 正向预查，在任何匹配 pattern 的字符串开始处匹配查找字符串。这是一个非获取匹配，也就是说，该匹配不需要获取供以后使用。 

(?!pattern) 负向预查，与(?=pattern)作用相反 

x|y 匹配 x 或 y。 

[xyz] 字符集合。 

[^xyz] 负值字符集合。 

[a-z] 字符范围，匹配指定范围内的任意字符。 

[^a-z] 负值字符范围，匹配任何不在指定范围内的任意字符。 

\b 匹配一个单词边界，也就是指单词和空格间的位置。

\B 匹配非单词边界。 

\cx 匹配由x指明的控制字符。 

\d 匹配一个数字字符。等价于 [0-9]。 

\D 匹配一个非数字字符。等价于 [^0-9]。 

\f 匹配一个换页符。等价于 \x0c 和 \cL。 

\n 匹配一个换行符。等价于 \x0a 和 \cJ。 

\r 匹配一个回车符。等价于 \x0d 和 \cM。 

\s 匹配任何空白字符，包括空格、制表符、换页符等等。等价于[ \f\n\r\t\v]。 

\S 匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。 

\t 匹配一个制表符。等价于 \x09 和 \cI。 

\v 匹配一个垂直制表符。等价于 \x0b 和 \cK。 

\w 匹配包括下划线的任何单词字符。等价于’[A-Za-z0-9_]’。 

\W 匹配任何非单词字符。等价于 ’[^A-Za-z0-9_]’。 

\xn 匹配 n，其中 n 为十六进制转义值。十六进制转义值必须为确定的两个数字长。

\num 匹配 num，其中num是一个正整数。对所获取的匹配的引用。 

\n 标识一个八进制转义值或一个后向引用。如果 \n 之前至少 n 个获取的子表达式，则 n 为后向引用。否则，如果 n 为八进制数字 (0-7)，则 n 为一个八进制转义值。 

\nm 标识一个八进制转义值或一个后向引用。如果 \nm 之前至少有is preceded by at least nm 个获取得子表达式，则 nm 为后向引用。如果 \nm 之前至少有 n 个获取，则 n 为一个后跟文字 m 的后向引用。如果前面的条件都不满足，若 n 和 m 均为八进制数字 (0-7)，则 \nm 将匹配八进制转义值 nm。 

\nml 如果 n 为八进制数字 (0-3)，且 m 和 l 均为八进制数字 (0-7)，则匹配八进制转义值 nml。 

\un 匹配 n，其中 n 是一个用四个十六进制数字表示的Unicode字符。

匹配中文字符的正则表达式： [u4e00-u9fa5]

匹配双字节字符(包括汉字在内)：[^x00-xff]

匹配空行的正则表达式：n[s| ]*r

匹配HTML标记的正则表达式：/<(.*)>.*</1>|<(.*) />/ 

匹配首尾空格的正则表达式：(^s*)|(s*$)

匹配Email地址的正则表达式：w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*

匹配网址URL的正则表达式：http://([w-]+.)+[w-]+(/[w- ./?%&=]*)?

利用正则表达式限制网页表单里的文本框输入内容：

用正则表达式限制只能输入中文：onkeyup="value=value.replace(/[^u4E00-u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^u4E00-u9FA5]/g,''))"

用正则表达式限制只能输入全角字符： onkeyup="value=value.replace(/[^uFF00-uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^uFF00-uFFFF]/g,''))"

用正则表达式限制只能输入数字：onkeyup="value=value.replace(/[^d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g,''))"

用正则表达式限制只能输入数字和英文：onkeyup="value=value.replace(/[W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g,''))"

=========常用正则式



匹配中文字符的正则表达式： [\u4e00-\u9fa5]

匹配双字节字符(包括汉字在内)：[^\x00-\xff]

匹配空行的正则表达式：\n[\s| ]*\r

匹配HTML标记的正则表达式：/<(.*)>.*<\/\1>|<(.*) \/>/ 

匹配首尾空格的正则表达式：(^\s*)|(\s*$)

匹配IP地址的正则表达式：/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //

匹配Email地址的正则表达式：\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

匹配网址URL的正则表达式：http://(/[\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

sql语句：^(select|drop|delete|create|update|insert).*$

1、非负整数：^\d+$ 

2、正整数：^[0-9]*[1-9][0-9]*$ 

3、非正整数：^((-\d+)|(0+))$ 

4、负整数：^-[0-9]*[1-9][0-9]*$ 

5、整数：^-?\d+$ 

6、非负浮点数：^\d+(\.\d+)?$ 

7、正浮点数：^((0-9)+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$ 

8、非正浮点数：^((-\d+\.\d+)?)|(0+(\.0+)?))$ 

9、负浮点数：^(-((正浮点数正则式)))$ 

10、英文字符串：^[A-Za-z]+$ 

11、英文大写串：^[A-Z]+$ 

12、英文小写串：^[a-z]+$ 

13、英文字符数字串：^[A-Za-z0-9]+$ 

14、英数字加下划线串：^\w+$ 

15、E-mail地址：^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$ 

16、URL：^[a-zA-Z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\s*)?$ 
或：^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$

17、邮政编码：^[1-9]\d{5}$

18、中文：^[\u0391-\uFFE5]+$

19、电话号码：^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$

20、手机号码：^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$

21、双字节字符(包括汉字在内)：^\x00-\xff

22、匹配首尾空格：(^\s*)|(\s*$)（像vbscript那样的trim函数）

23、匹配HTML标记：<(.*)>.*<\/\1>|<(.*) \/> 

24、匹配空行：\n[\s| ]*\r

25、提取信息中的网络链接：(h|H)(r|R)(e|E)(f|F) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)?

26、提取信息中的邮件地址：\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

27、提取信息中的图片链接：(s|S)(r|R)(c|C) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)?

28、提取信息中的IP地址：(\d+)\.(\d+)\.(\d+)\.(\d+)

29、提取信息中的中国手机号码：(86)*0*13\d{9}

30、提取信息中的中国固定电话号码：(\(\d{3,4}\)|\d{3,4}-|\s)?\d{8}

31、提取信息中的中国电话号码（包括移动和固定电话）：(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}

32、提取信息中的中国邮政编码：[1-9]{1}(\d+){5}

33、提取信息中的浮点数（即小数）：(-?\d*)\.?\d+

34、提取信息中的任何数字 ：(-?\d*)(\.\d+)? 

35、IP：(\d+)\.(\d+)\.(\d+)\.(\d+)

36、电话区号：/^0\d{2,3}$/

37、腾讯QQ号：^[1-9]*[1-9][0-9]*$

38、帐号(字母开头，允许5-16字节，允许字母数字下划线)：^[a-zA-Z][a-zA-Z0-9_]{4,15}$

39、中文、英文、数字及下划线：^[\u4e00-\u9fa5_a-zA-Z0-9]+$

*/


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO; 　
using System.Data;
using System.Reflection;
using System.Linq;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;//引入正则表达式命名空间

namespace msBsc.SvRef
{
    public partial class Number2English
    {
        private readonly string[] StrNO = new string[19];
        private readonly string[] StrTens = new string[9];
        private readonly string[] Unit = new string[8];

        public string NumToString(double Number)
        {
            return NumberToString(Number);
        }
        public string NumberToString(double Number)
        {
            string Str;
            string BeforePoint;
            string AfterPoint;
            string tmpStr;
            int nBit;
            string CurString;
            int nNumLen;
            Init();
            Str = Convert.ToString(Math.Round(Number, 2));
            if (Str.IndexOf(".") == -1)
            {
                BeforePoint = Str;
                AfterPoint = "";
            }
            else
            {
                BeforePoint = Str.Substring(0, Str.IndexOf("."));
                AfterPoint = Str.Substring(Str.IndexOf(".") + 1, Str.Length - Str.IndexOf(".") - 1);
                AfterPoint = AfterPoint.TrimEnd('0');
            }
            if (BeforePoint.Length > 12)
            {
                return null;
            }
            Str = "";
            if (BeforePoint != string.Empty && int.Parse(BeforePoint) == 0)
            {
                if (AfterPoint.Trim() != string.Empty)
                {
                    Str = "Naught";
                }
                else
                {
                    Str = "Zero";
                }
            }
            else
            {
                while (BeforePoint.Length > 0)
                {
                    nNumLen = Len(BeforePoint);
                    if (nNumLen % 3 == 0)
                    {
                        CurString = Left(BeforePoint, 3);
                        BeforePoint = Right(BeforePoint, nNumLen - 3);
                    }
                    else
                    {
                        CurString = Left(BeforePoint, (nNumLen % 3));
                        BeforePoint = Right(BeforePoint, nNumLen - (nNumLen % 3));
                    }
                    nBit = Len(BeforePoint) / 3;
                    tmpStr = DecodeHundred(CurString);
                    if ((BeforePoint == Len(BeforePoint).ToString() || nBit == 0) && Len(CurString) == 3)
                    {
                        if (Convert.ToInt32(Left(CurString, 1)) != 0 & Convert.ToInt32(Right(CurString, 2)) != 0)
                        {
                            tmpStr = Left(tmpStr, tmpStr.IndexOf(Unit[3]) + Len(Unit[3])) + Unit[7] + " " +
                                     Right(tmpStr, Len(tmpStr) - (tmpStr.IndexOf(Unit[3]) + Len(Unit[3])));
                        }
                        else
                        {
                            tmpStr = Unit[7] + " " + tmpStr;
                        }
                    }
                    if (nBit == 0)
                    {
                        Str = Convert.ToString(Str + " " + tmpStr).Trim();
                    }
                    else
                    {
                        Str = Convert.ToString(Str + " " + tmpStr + " " + Unit[nBit - 1]).Trim();
                    }
                    if (Left(Str, 3) == Unit[7])
                    {
                        Str = Convert.ToString(Right(Str, Len(Str) - 3)).Trim();
                    }
                    if (BeforePoint == Len(BeforePoint).ToString())
                    {
                        return "";
                    }
                }
            }
            BeforePoint = Str;
            if (Len(AfterPoint) > 0)
            {
                //AfterPoint = Unit[5] + " " + DecodeHundred(AfterPoint) + " " + Unit[6];美元读法
                AfterPoint = "Point " + DecodeHundred(AfterPoint);
            }
            //else
            //{
            //    AfterPoint = Unit[4];
            //}
            return (BeforePoint + " " + AfterPoint).ToUpper();
        }

        private void Init()
        {
            if (StrNO[0] != "One")
            {
                StrNO[0] = "One";
                StrNO[1] = "Two";
                StrNO[2] = "Three";
                StrNO[3] = "Four";
                StrNO[4] = "Five";
                StrNO[5] = "Six";
                StrNO[6] = "Seven";
                StrNO[7] = "Eight";
                StrNO[8] = "Nine";
                StrNO[9] = "Ten";
                StrNO[10] = "Eleven";
                StrNO[11] = "Twelve";
                StrNO[12] = "Thirteen";
                StrNO[13] = "Fourteen";
                StrNO[14] = "Fifteen";
                StrNO[15] = "Sixteen";
                StrNO[16] = "Seventeen";
                StrNO[17] = "Eighteen";
                StrNO[18] = "Nineteen";
                StrTens[0] = "Ten";
                StrTens[1] = "Twenty";
                StrTens[2] = "Thirty";
                StrTens[3] = "Forty";
                StrTens[4] = "Fifty";
                StrTens[5] = "Sixty";
                StrTens[6] = "Seventy";
                StrTens[7] = "Eighty";
                StrTens[8] = "Ninety";
                Unit[0] = "Thousand";
                Unit[1] = "Million";
                Unit[2] = "Billion";
                Unit[3] = "Hundred";
                Unit[4] = "Only";
                Unit[5] = "Dollars and";
                Unit[6] = "Cent";
                Unit[7] = "";
            }
        }

        private string DecodeHundred(string HundredString)
        {
            int tmp;
            string rtn = "";
            if (Len(HundredString) > 0 && Len(HundredString) <= 3)
            {
                switch (Len(HundredString))
                {
                    case 1:
                        tmp = Convert.ToInt32(HundredString);
                        if (tmp != 0)
                        {
                            rtn = StrNO[tmp - 1];
                        }
                        break;
                    case 2:
                        tmp = Convert.ToInt32(HundredString);
                        if (tmp != 0)
                        {
                            if ((tmp < 20))
                            {
                                rtn = StrNO[tmp - 1];
                            }
                            else
                            {
                                if (Convert.ToInt32(Right(HundredString, 1)) == 0)
                                {
                                    rtn = StrTens[Convert.ToInt32(tmp / 10) - 1];
                                }
                                else
                                {
                                    rtn =
                                            Convert.ToString(StrTens[Convert.ToInt32(tmp / 10) - 1] + " " +
                                                             StrNO[Convert.ToInt32(Right(HundredString, 1)) - 1]);
                                }
                            }
                        }
                        break;
                    case 3:
                        if (Convert.ToInt32(Left(HundredString, 1)) != 0)
                        {
                            rtn =
                                    Convert.ToString(StrNO[Convert.ToInt32(Left(HundredString, 1)) - 1] + " " + Unit[3] +
                                                     "AND " +
                                                     DecodeHundred(Right(HundredString, 2)));
                        }
                        else
                        {
                            rtn = DecodeHundred(Right(HundredString, 2));
                        }
                        break;
                    default:
                        break;
                }
            }
            return rtn;
        }

        private string Left(string str, int n)
        {
            return str.Substring(0, n);
        }

        private string Right(string str, int n)
        {
            return str.Substring(str.Length - n, n);
        }

        private int Len(string str)
        {
            return str.Length;
        }
    } 


    public partial class CString
    {
        /// <summary>
        /// 字符编码转换
        /// </summary>
        /// <param name="fromCoding"></param>
        /// <param name="toCoding"></param>
        /// <returns></returns>
        public static string StrEncodingConvert(string strOld,System.Text.Encoding fromCoding, System.Text.Encoding toCoding)
        {
            try
            {

                byte[] bytes = System.Text.Encoding.Convert(
                    fromCoding,
                       //System.Text.Encoding.UTF8,//swfupload默认是用utf-8上传的，如果是其它编码，则改成其它编码

                       toCoding,
                       //System.Text.Encoding.Default,

                       toCoding.GetBytes(strOld));//关键是这句，强制转换编码
                       //System.Text.Encoding.Default.GetBytes(strOld));//关键是这句，强制转换编码

                using (Stream stream = new MemoryStream(bytes))
                {

                    //using (StreamReader objReader = new StreamReader(stream, System.Text.Encoding.Default))
                    using (StreamReader objReader = new StreamReader(stream, toCoding))
                    {
                        strOld = objReader.ReadToEnd();//正确的文件名

                        objReader.Close();

                        objReader.Dispose();
                    }
                }
            }

            catch (Exception) { }
            return strOld;
        }

        public static long GeneratelongId()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }

        public static string GenerateStrId()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
            {
                i *= ((int)b + 1);
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

        public static bool GetContainsStr(string strParent, string strChild)
        {
            strParent = strParent.Replace("\r", "").Replace("\n", "").TrimEnd().TrimStart();
            strChild = strChild.Replace("\r", "").Replace("\n", "").TrimEnd().TrimStart();
            return strParent.Contains(strChild)  ;
        }

        public static string GetCheckBoxHtml(string strpId, string strNme, string strckbAttr, string strlabAttr)
        {
            return "<input id='ckb" + strpId + "' type='checkbox' name='ckb" + strpId + "' " + strckbAttr + "/><label for='ckb" + strpId + "' " + strlabAttr + ">" + strNme + "</label>";
        }

        public static string GetImgHtml(string strpClassNme, string strUrl)
        {
            if (strUrl != string.Empty)
            {
                return "<img src='" + msBsc.AppLogic.Cfg.SystemFileDir.FileDir.httpUrlBase + strUrl + "' height='14px' align='absmiddle'/>";
            }
            else
            {
                return "<img class='" + strpClassNme + "' height='14px' align='absmiddle'/>";
            }
        }

        public static string GetStautsImgHtml(string strpStatus)
        {
            return "<img src='" + msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + "images/Gif16/Label" + (strpStatus == string.Empty ? "0" : strpStatus) + ".gif' height='14px' align='absmiddle'/>"; 
        }
        
        /// <summary>
        /// 获取按钮代码CSS3格式
        /// </summary>
        /// <param name="strpBtnId"></param>
        /// <param name="strBtnTxt"></param>
        /// <param name="strpClass"></param>
        /// <param name="strpScript"></param>
        /// <returns></returns>
        public static string GetButtonHtml(string strpBtnId,string strBtnTxt,string strpClass, string strpScript)
        {
            return "<span style='display:inline;'><button type='button' " + (strpBtnId == string.Empty ? "" : "id='" + strpBtnId + "' name='" + strpBtnId + "'") + " class='"+(strpClass==string.Empty?"btn btn-warning":strpClass)+"' onclick='eval(unescape(\"" + Microsoft.JScript.GlobalObject.escape(strpScript) + "\"));return false;'><i class='ico-share'></i><span>" + strBtnTxt + "</span></button></span>"; 
        }

        public static string GetALinkHtml(string strpAnme,string strpUrl)
        {
            return "<a href=\"javascript:void(0);\" onclick=\"window.location.href=unescape('" + Microsoft.JScript.GlobalObject.escape(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.httpUrlBase + strpUrl) + "');return false;\">" + strpAnme + "</a>"; 
        }
        public static string GetAScriptHtml(string strpAnme, string strpScript, string strpAttr)
        {
            return "<a href=\"javascript:void(0);\" onclick=\"eval(unescape('" + Microsoft.JScript.GlobalObject.escape(strpScript) + "'));return false;\" " + strpAttr + ">" + strpAnme + "</a>";
        }

        public static string GetHeaderHtmlByTemp(string strp1, string strp2)
        {
            string sHtml = "";
            sHtml += " <div id=\"spmt_header\" width=\"100%\"><div class=\"sm_l\"></div>";
            sHtml += "     <div id=\"spmt_statustxt\">" + strp1;

            sHtml += "  </div>";
            sHtml += "    <div class=\"sm_r\"></div><div id=\"spmt_finder\">";
            sHtml += "<span class=\"no\">" + strp2 + " </span>";
            sHtml += "&nbsp&nbsp</div>";
            sHtml += "  </div>";
            sHtml += "     <div id=\"divspmt_more\"><div class=\"sm_l\"></div><div class=\"sm_c\"></div><div class=\"sm_r\"></div></div>";

            return sHtml;
        }

        /// <summary>
        /// [A-Z|a-z|0-9]{1,}   字母或数字开始的字符串,不能为空
        /// </summary>
        /// <param name="strSrcString"></param>
        /// <returns></returns>
        public static bool ValidateForCharNum(string strSrcString)
        {
            bool blRet = false; 
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("[A-Z|a-z|0-9]{1,}",
                System.Text.RegularExpressions.RegexOptions.Compiled);
            System.Text.RegularExpressions.Match m = r.Match(strSrcString);
            if (m.Success && strSrcString ==m.Value)
            {
                blRet = true;
            } 
            return blRet;
        }
        
        
        
        ///str_value 字符
        ///str_len 要截取的字符长度
        public static string leftx(string str_value, int str_len)
        {
            int p_num = 0;
            int i;
            string New_Str_value = "";

            if (str_value == "")
            {
                New_Str_value = "";
            }
            else
            {
                int Len_Num = str_value.Length;



                //if (Len_Num < str_len)
                //{
                // str_len = Len_Num;
                //}


                for (i = 0; i <= Len_Num - 1; i++)
                {
                    //str_value.Substring(i,1);
                    if (i > Len_Num) break;
                    char c = Convert.ToChar(str_value.Substring(i, 1));
                    if (((int)c > 255) || ((int)c < 0))
                    {
                        p_num = p_num + 2;

                    }
                    else
                    {
                        p_num = p_num + 1;

                    }

                    if (p_num >= str_len)
                    {

                        New_Str_value = str_value.Substring(0, i + 1);

                        break;
                    }
                    else
                    {
                        New_Str_value = str_value;
                    }

                }

            }
            return New_Str_value;
        }


        /// <summary>
        /// 转半角的函数(DBC case)
        /// </summary>
        /// <param name="input">任意字符串</param>
        /// <returns>半角字符串</returns>
        ///<remarks>
        ///全角空格为12288，半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
        ///</remarks>
        public static string ToDBC(string input)
        {
            input = input.Replace('\t', ' ').Replace('，', ',').Replace('‘', '\'').Replace('’', '\'').Replace('。', '.');
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;

                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)

                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }
        public static bool GetIsHasCHChar(string str, out string CHChar)
        {
            CharEnumerator ce = str.GetEnumerator();
            while (ce.MoveNext())
            {
                bool bltem1 = (ce.Current > 0 && ce.Current < 255 && ce.Current != '×') ? false : true;
                if (bltem1)
                {
                    CHChar = ce.Current.ToString(); 
                    return true;
                }
            }
            CHChar = ""; 
            return false;
        }
        /// <summary>
        /// 获取表指定条件下指定字段的值的数组, 返回没有重复值,不含已删除的记录
        /// </summary>
        /// <param name="dtpTable"></param>
        /// <param name="strpFilter"></param>
        /// <param name="strpField"></param>
        /// <returns></returns>
        public static string[] GetRowsFieldValueArry(DataTable dtpTable,string strpFilter, string strpField)
        {
            DataRow[] arrprow = dtpTable.Select(strpFilter);
            return GetRowsFieldValueArry(arrprow, strpField);
        }

        /// <summary>
        /// 获取指定字段的值的数组, 返回没有重复值,不含已删除的记录
        /// </summary>
        /// <param name="arrprow"></param>
        /// <param name="strpField"></param>
        /// <returns></returns>
        public static string[] GetRowsFieldValueArry(DataRow[] arrprow,string strpField)
        {
            var aaaa = (from p in arrprow where p.RowState != DataRowState.Deleted select p[strpField].ToString());
            if (aaaa != null && aaaa.Count() > 0)
            {
                return aaaa.Distinct().ToArray();
            }
            return new string[] { };
        }

        /// <summary>
        /// 获取记录的JSON编码
        /// </summary>
        /// <param name="drw"></param>
        /// <returns></returns>
        public static string DataRowToJson(DataRow drw)
        {
            if (drw == null)
            {
                return "";
            }
            StringBuilder sbJson = new StringBuilder();

            sbJson.Append("{");
            for (int c = 0; c < drw.Table.Columns.Count; c++)
            {
                if (c > 0)
                {
                    sbJson.Append(",");
                }
                sbJson.Append(drw.Table.Columns[c].ToString() + ":\"" + stringToJson(drw[c].ToString()) + "\"");
            }
            sbJson.Append("}");
            return sbJson.ToString();
        }

        public static DataRow GetDataRowByJson(string jsonText)
        {

            DataTable dtRet = new DataTable();


            JavaScriptSerializer s = new JavaScriptSerializer();

            Dictionary<string, object> JsonData = (Dictionary<string, object>)s.DeserializeObject(jsonText);

            //Dictionary<string, object> dataSet = (Dictionary<string, object>)JsonData["dataSet"];

            //Dictionary<string, object> header = (Dictionary<string, object>)dataSet["header"];

            //Dictionary<string, object> fieldDefine = (Dictionary<string, object>)dataSet["header"];

            //Dictionary<string, object> data = (Dictionary<string, object>)dataSet["data"];

            //object[] rows = (object[])data["row"];

            //gsr.header.Version = header["version"].ToString();

            //gsr.header.ErrorInfo = header["errorInfo"].ToString();

            //gsr.header.ReturnCode = header["returnCode"].ToString();

            //gsr.header.ReturnRows = Convert.ToInt16(header["returnRows"]);

            //gsr.header.TotalRows = Convert.ToInt16(header["totalRows"]);


            //Dictionary<string, object> dicFieldDefine = (Dictionary<string, object>)dataSet["fieldDefine"];

            DataRow drRet=dtRet.NewRow();
            dtRet.Rows.Add(drRet);
            foreach (KeyValuePair<string, object> ss in JsonData)
            {
                dtRet.Columns.Add(ss.Key, typeof(string));
                drRet[ss.Key] = ss.Value;
            }


            return drRet;

        }

        public static string stringToJson(string s)
        {
            return s.Replace("\\", "\\\\")
                .Replace("\t", "\\t")
                .Replace("\r", "\\r")
                .Replace("\n", "\\n")
                .Replace("\f", "\\f")
                .Replace("\b", "\\b")
                .Replace("/", "\\/")
                .Replace("\'", "\\\'")
                .Replace("\"", "\\\"");
            //return  Microsoft.JScript.GlobalObject.encodeURIComponent(s);
            //StringBuilder sb = new StringBuilder();
            //for (int i = 0; i < s.Length; i++)
            //{
            //    char c = s[i];
            //    switch (c)
            //    {
            //        case '\"':
            //            sb.Append("\\\"");
            //            break;
            //        case '\'':
            //            sb.Append("\\\'");
            //            break;
            //        case '\\':
            //            sb.Append("\\\\");
            //            break;
            //        case '/':
            //            sb.Append("\\/");
            //            break;
            //        case '\b':
            //            sb.Append("\\b");
            //            break;
            //        case '\f':
            //            sb.Append("\\f");
            //            break;
            //        case '\n':
            //            sb.Append("\\n");
            //            break;
            //        case '\r':
            //            sb.Append("\\r");
            //            break;
            //        case '\t':
            //            sb.Append("\\t");
            //            break;
            //        default:
            //            sb.Append(c);
            //            break;
            //    }
            //}
            //return sb.ToString();
        }

        /// <summary>
        /// 获取字符串中指定位置开始的指定长度的字符串，支持汉字英文混合 汉字为2字节计数
        /// </summary>
        /// <param name="strSub">输入中英混合字符串</param>
        /// <param name="start">开始截取的起始位置</param>
        /// <param name="length">要截取的字符串长度</param>
        /// <returns></returns>
        public static string GetSubString(string strSub, int start, int length)
        {
            string temp = strSub;
            int j = 0, k = 0, p = 0;

            CharEnumerator ce = temp.GetEnumerator();
            while (ce.MoveNext())
            {
                j += (ce.Current > 0 && ce.Current < 255 && ce.Current != '×') ? 1 : 2;

                if (j <= start)
                {
                    p++;
                }
                else
                {
                    if (j == GetLength(temp))
                    {
                        temp = temp.Substring(p, k + 1);
                        break;
                    }
                    if (j <= length + start)
                    {
                        k++;
                    }
                    else
                    {
                        temp = temp.Substring(p, k);
                        break;
                    }
                }
            }

            return temp;
        }


        /// <summary>
        /// 计算文本长度，区分中英文字符，中文算两个长度，英文算一个长度

        /// <seealso cref="Common_Function.Text_Length"/>
        /// </summary>
        /// <param name="Text">需计算长度的字符串</param>
        /// <returns>int</returns>
        public static int Text_Length(string Text)
        {
            int len = 0;

            for (int i = 0; i < Text.Length; i++)
            {
                byte[] byte_len = Encoding.Default.GetBytes(Text.Substring(i, 1));
                if (byte_len.Length > 1)
                    len += 2;
                else
                    len += 1;
            }

            return len;
        }

        public static int HowLongText(String str)
        {
            //将所有的双字节替换成'aa'进行判断
            str = Regex.Replace(str, "[^-x00-xff ~!@#$%&*()_+|\\={};:\'\"/?.,<>]", "aa");
            return str.Length;
        }



        /// <summary>
        /// 获取指定字符串长度，汉字以2字节计算
        /// </summary>
        /// <param name="aOrgStr">要统计的字符串</param>
        /// <returns></returns>
        public static int GetLength(String aOrgStr)
        {
            int intLen = aOrgStr.Length;
            int i;
            char[] chars = aOrgStr.ToCharArray();
            for (i = 0; i < chars.Length; i++)
            {
                if (System.Convert.ToInt32(chars[i]) > 255 || chars[i] == '×')
                {
                    intLen++;
                }
            }
            return intLen;
        }

        public static string GetSubString(string str, int length)
        {
            string temp = str;
            int j = 0, k = 0;

            CharEnumerator ce = str.GetEnumerator();
            while (ce.MoveNext())
            {
                j += (ce.Current > 0 && ce.Current < 255 && ce.Current != '×') ? 1 : 2;

                if (j <= length)
                {
                    k++;
                }
                else
                {
                    temp = str.Substring(0, k);
                    break;
                }
            }

            return temp;
        }

        public static string GetSubString(string str, int length, char AfterPadChar)
        {
            string temp = str;
            int j = 0, k = 0;

            CharEnumerator ce = str.GetEnumerator();
            while (ce.MoveNext())
            {
                int oldJ = j;
                j += (ce.Current > 0 && ce.Current < 255 && ce.Current != '×') ? 1 : 2;

                if (j <= length)
                {
                    k++;
                }
                else
                {
                    temp = str.Substring(0, k);
                    for (int i = 0; i < length - oldJ; i++)
                    {
                        temp = temp + AfterPadChar;
                    }
                    break;
                }
            }

            return temp;
        }
        public static string StringPadLeft(string str, int length, char AfterPadChar)
        {
            string temp = str;
            int j = 0, k = 0;

            CharEnumerator ce = str.GetEnumerator();
            while (ce.MoveNext())
            {
                int oldJ = j;
                j += (ce.Current > 0 && ce.Current < 255 && ce.Current != '×') ? 1 : 2;

                if (j <= length)
                {
                    k++;
                }
                else
                {
                    temp = str.Substring(0, k);
                    for (int i = 0; i < length - oldJ; i++)
                    {
                        temp = AfterPadChar + temp;
                    }
                    //j = length;
                    break;
                }
            }
            if (j <= length)
            {
                for (int i = 0; i < length - j; i++)
                {
                    temp = AfterPadChar + temp;
                }
            }

            return temp;
        }

        public static string StringPadRight(string str, int length, char AfterPadChar)
        {
            string temp = str;
            int j = 0, k = 0;

            CharEnumerator ce = str.GetEnumerator();
            while (ce.MoveNext())
            {
                int oldJ = j;
                j += (ce.Current > 0 && ce.Current < 255 && ce.Current != '×') ? 1 : 2;

                if (j <= length)
                {
                    k++;
                }
                else
                {
                    temp = str.Substring(0, k);
                    for (int i = 0; i < length - oldJ; i++)
                    {
                        temp = temp + AfterPadChar;
                    }
                    //j = length;
                    break;
                }
            }
            if (j <= length)
            {
                for (int i = 0; i < length - j; i++)
                {
                    temp = temp + AfterPadChar;
                }
            }

            return temp;
        }
        public static string EdiFormatTwIfcusm(string str)
        {
            return EdiFormatTwIfcusm(str, -1);
        }
        public static void EdiFormatOnline(StreamWriter sw, ref int t_num, string strPreString, string strSrc, int iRecrdSum, int iOneRecordLineSum, int iLineCharSum)
        {
            //Dictionary<string, string> JsonData2 = new Dictionary<string, string>(); 
            string[] arrstrstrShipper1 = strSrc.Replace("\r\n", "\r").Split(new char[] { '\r', '\n' });
            string strString = strPreString;
            //strString += ":" + BseClass.CString.EdiFormatTwIfcusm(drDocutem1["SHIPPER_PARTNER_CDE"].ToString());
            if (arrstrstrShipper1.Length > 0)
            {
                int ilineSum1 = 0;
                for (int p = 0; p < arrstrstrShipper1.Length; p++)
                {
                    //if (!string.IsNullOrEmpty(arrstrstrShipper1[p]))
                    //{
                    string strLinetem1 = arrstrstrShipper1[p];
                    bool blNotOver = true;
                    while (blNotOver)// (strLinetem1 != string.Empty)
                    {
                        string strLinetem2 = msBsc.SvRef.CString.EdiFormatTwIfcusm(strLinetem1, iLineCharSum);
                        int iLineLengthtem1 = strLinetem1.Length;
                        int iLineLengthtem2 = strLinetem2.Length;
                        if (iLineLengthtem1 > iLineLengthtem2)
                            strLinetem1 = strLinetem1.Substring(iLineLengthtem2, iLineLengthtem1 - iLineLengthtem2);
                        else
                        {
                            blNotOver = false;
                            strLinetem1 = "";
                        }




                        ilineSum1 = ilineSum1 + 1;
                        if (ilineSum1 / iOneRecordLineSum >= iRecrdSum)
                            break;
                        if (ilineSum1 > iOneRecordLineSum && ilineSum1 % iOneRecordLineSum == 1)
                        {
                            sw.WriteLine(strString + "'");
                            t_num = t_num + 1;
                            strString = strPreString;
                        }
                        strString += ":" + strLinetem2;
                    }
                    //}
                }
            }
            else
            {
                strString += ":";
            }
            if (strString == strPreString)
                strString = strPreString + ":";

            sw.WriteLine(strString + "'");
            t_num = t_num + 1;

        }

        public static string EdiFormatTwIfcusm(string str, int iLengt)
        {
            str = str.Replace("\r", " ").Replace("\n", " ");
            str = str.Replace("?", "??");
            str = str.Replace(":", "?:");
            str = str.Replace("+", "?+");
            str = str.Replace("'", "?'");
            if (iLengt != -1)
            {
                str = GetSubString(str, iLengt);
            }
            return str;
        }
        public static string EdiJoinStrTwIfcusm(string separater, string[] Array)
        {
            string strJoinString = string.Join(separater, Array);
            return strJoinString + "'";

        }


        /// <summary>
        /// 将以:分隔的一行数据转换为字符串数组
        /// </summary>
        /// <param name="sLine"></param>
        /// <returns></returns>
        public static string[] SplitEdiLine(string sLine)
        {
            if (sLine == string.Empty)
            {
                return new string[] { "    " };
            }
            if (sLine.EndsWith("'"))
            {
                sLine = sLine.Substring(0, sLine.Length - 1);
            }
            Dictionary<string, string> JsonData2 = new Dictionary<string, string>();// (Dictionary<string, object>);
            int iCharStart = 0;
            for (int i = 0; i < sLine.Length; i++)
            {
                if (sLine[i] == ':')
                {
                    if (i > 0 && sLine[i - 1] == '?')
                    {
                        continue;
                    }
                    else
                    {
                        string strtem1 = sLine.Substring(iCharStart, i - iCharStart);
                        strtem1 = strtem1.Replace("??", "?").Replace("?:", ":").Replace("?'", "'");
                        JsonData2.Add(iCharStart.ToString(), strtem1);
                        iCharStart = i + 1;
                    }
                }
                else if (i == sLine.Length - 1)
                {
                    string strtem1 = sLine.Substring(iCharStart, sLine.Length - i);
                    strtem1 = strtem1.Replace("??", "?").Replace("?:", ":").Replace("?'", "'");
                    JsonData2.Add(iCharStart.ToString(), strtem1);
                    iCharStart = i + 1;
                }
            }
            string[] arrtem1 = new string[JsonData2.Count];
            JsonData2.Values.CopyTo(arrtem1, 0);
            return arrtem1;
        }

        /// <summary>
        /// 按长度，将一行数据转化为数组，遇汉字前半截不取
        /// </summary>
        /// <param name="strLine"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static string[] SplitEdiLineByLength(string strLine, params object[] args)
        {
            string strtem1 = strLine;
            string[] arrret = new string[args.Length];
            for (int i = 0; i < args.Length; i++)
            {
                arrret[i] = GetSubString(strtem1, (int)args[i]);
                strtem1 = strtem1.Substring(arrret[i].Length, strtem1.Length - arrret[i].Length);
            }

            return arrret;
        }

        /// <summary>
        /// 按指定长度的一行字符分隔为数组返回
        /// </summary>
        /// <param name="strLine"></param>
        /// <param name="ileng"></param>
        /// <returns></returns>
        public static string[] SplitStrByLineLeng(string strLine, int ileng, bool blNotSplitWords)
        {
            string strtem1 = strLine;
            string[] arrret = new string[0];
            while (strtem1 != string.Empty)
            {
                string strlinetm1 = GetSubString(strtem1, ileng);
                if (blNotSplitWords)
                {
                    string strlinetm2 = strtem1.Substring(strlinetm1.Length, strtem1.Length - strlinetm1.Length);
                    if (!strlinetm1.EndsWith(" ") && !strlinetm2.StartsWith(" ") && strlinetm2.Length > 0)
                    {
                        int item333 = strlinetm1.LastIndexOf(" ");
                        if (strlinetm1.LastIndexOf(",") > item333)
                        {
                            item333 = strlinetm1.LastIndexOf(",");
                        }
                        if (item333 != -1)
                        {
                            strlinetm1 = GetSubString(strtem1, item333 + 1);
                        }
                    }
                }

                arrret = arrret.Concat(new string[1] { strlinetm1 }).ToArray();

                strtem1 = strtem1.Substring(strlinetm1.Length, strtem1.Length - strlinetm1.Length);
            } 
            return arrret;
        }

        /// <summary>
        /// 将字符串按指定长度换行后返回
        /// </summary>
        /// <param name="strOld"></param>
        /// <param name="ileng"></param>
        /// <returns></returns>
        public static string GetSplitStrByLineLeng(string strOld, int ileng, bool blNotSplitWords)
        {
            strOld = strOld.Replace("\r\n", "\r");
            strOld = strOld.Replace("\r", "\n");
            string[] arrtem11 = strOld.Split('\n');
            string strRettem1 = "";
            for (int i = 0; i < arrtem11.Length; i++)
            {
                string[] arrret = msBsc.SvRef.CString.SplitStrByLineLeng(arrtem11[i], ileng, blNotSplitWords);
                strRettem1 += strRettem1 == "" ? string.Join("\r\n", arrret) : "\r\n" + string.Join("\r\n", arrret); 
                //for (int r = 0; r < arrret.Length; r++)
                //{
                //    strRettem1 += strRettem1 == "" ? arrret[r] : "\r\n" + arrret[r];
                //}
            }
            return strRettem1;
        }

        public static string[] GetSplitStrByMemoLeng(string strOld, int ileng, bool blNotSplitWords, int iLineAfterAddStr, string strLineAfterAddStr)
        {
            strOld = strOld.Replace("\r\n", "\r");
            strOld = strOld.Replace("\r", "\n");
            string[] arrtem11 = strOld.Split('\n'); 
            string[] arrRettem222=new string[] {};
            //int iLineTem1 = 0;
            bool blIsAddAfterStr = false;
            bool blIsAddNextAfterStr = false;
            for (int i = 0; i < arrtem11.Length; i++)
            {
                if (!blIsAddNextAfterStr && blIsAddAfterStr)
                {
                    arrtem11[i] = "\r\n" + strLineAfterAddStr + arrtem11[i];
                    blIsAddNextAfterStr = true;
                }
                string[] arrret = msBsc.SvRef.CString.SplitStrByLineLeng(arrtem11[i], ileng, blNotSplitWords);
                if (!blIsAddAfterStr && iLineAfterAddStr > 0 && (arrRettem222.Length + arrret.Length >= iLineAfterAddStr || arrRettem222.Length + 1 == iLineAfterAddStr && i+1<arrtem11.Length))
                {

                    for (int r = 0; r < arrret.Length; r++)
                    {
                        if (arrRettem222.Length + r + 1 == iLineAfterAddStr && (arrret.Length != r + 1 || arrtem11.Length!=i+1))
                        {
                            arrret[r] = arrret[r].TrimEnd();
                            int itemm3333222 = GetLength(arrret[r] + strLineAfterAddStr);
                            if (itemm3333222 > ileng)
                            {
                                string strtme3333 = arrret[r];
                                string strtme3335 = "";
                                while (GetLength(strtme3333 + strLineAfterAddStr) > ileng)
                                {
                                    int iLastBlandtem1 = -1;
                                    if (blNotSplitWords)
                                    {
                                        iLastBlandtem1 = strtme3333.LastIndexOf(' ');
                                        if (strtme3333.LastIndexOf(',') > iLastBlandtem1)
                                        {
                                            iLastBlandtem1 = strtme3333.LastIndexOf(',');
                                        }
                                        if (strtme3333.EndsWith(" ") || strtme3333.EndsWith(","))
                                        {
                                            iLastBlandtem1 = iLastBlandtem1 - 1;
                                        }
                                    }
                                    else
                                    {
                                        iLastBlandtem1 = strtme3333.Length - 2;
                                    }
                                    strtme3335 = strtme3333.Substring(iLastBlandtem1 + 1) + strtme3335;
                                    strtme3333 = strtme3333.Substring(0, iLastBlandtem1 + 1);
                                }
                                if (r < arrret.Length - 1)
                                {
                                    arrret[r] = strtme3333 + strLineAfterAddStr;
                                    arrret[r + 1] = strLineAfterAddStr + strtme3335 + arrret[r + 1];
                                }
                                else
                                {
                                    arrret[r] = strtme3333 + strLineAfterAddStr + "\r\n" + strLineAfterAddStr + strtme3335;
                                }
                                blIsAddNextAfterStr = true;
                            }
                            else
                            {
                                arrret[r] = arrret[r] + strLineAfterAddStr;
                            }
                        }
                        if (!blIsAddNextAfterStr && arrRettem222.Length + r + 1 > iLineAfterAddStr)
                        {
                            arrret[r] = "\r\n" + strLineAfterAddStr + arrret[r];
                            blIsAddNextAfterStr = true;
                        }
                    }

                    arrret = GetSplitStrByMemoLeng(string.Join("\r\n", arrret), ileng, blNotSplitWords,-1,"");
                    blIsAddAfterStr = true;
                }
                arrRettem222=arrRettem222.Concat(arrret).ToArray();
                //strRettem1 += strRettem1 == "" ? string.Join("\r\n", arrret) : "\r\n" + string.Join("\r\n", arrret); 
                //for (int r = 0; r < arrret.Length; r++)
                //{
                //    strRettem1 += strRettem1 == "" ? arrret[r] : "\r\n" + arrret[r];
                //}
                //iLineTem1 += arrret.Length;
            }
            return arrRettem222;
        }

        ///// <summary>
        ///// 按原来的换行和每行要求的长度转换为数组
        ///// </summary>
        ///// <param name="strOld"></param>
        ///// <param name="ileng"></param>
        ///// <param name="blNotSplitWords"></param>
        ///// <param name="iLineAfterAddStr"></param>
        ///// <param name="strLineAfterAddStr"></param>
        ///// <returns></returns>
        //public static string[] GetSplitStrByMemoLeng(string strOld, int ileng, bool blNotSplitWords, int iLineAfterAddStr, string strLineAfterAddStr)
        //{
        //    strOld = GetSplitStrByLineLeng(strOld, ileng, blNotSplitWords, iLineAfterAddStr, strLineAfterAddStr);
        //    strOld = strOld.Replace("\r\n", "\r");
        //    strOld = strOld.Replace("\r", "\n");
        //    string[] arrtem11 = strOld.Split('\n');
        //    return arrtem11;
        //}

        public static string MoneyDecimalToChineseMonay(Decimal MoneyDecimal)
        {
            bool negative = false;
            if (MoneyDecimal < 0)
            {
                negative = true;
                MoneyDecimal = -MoneyDecimal;
            }
            string[] BitStrChinese = { "", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
            Int64 i = Convert.ToInt64((MoneyDecimal * 1000) / 100);
            Int64 intMoney = i / 10;
            string strChineseMoney = intMoney == 0 ? string.Empty : IntToChineseMoney(intMoney);
            int j = Convert.ToInt32((MoneyDecimal * 100) % 100);
            if (j == 0) strChineseMoney += "整";
            else if (j < 10) strChineseMoney += "零" + BitStrChinese[j] + "分";
            else if (j % 10 == 0) strChineseMoney += BitStrChinese[j / 10] + "角整";
            else strChineseMoney += BitStrChinese[j / 10] + "角" + BitStrChinese[j % 10] + "分";
            if (negative)
                strChineseMoney = "负" + strChineseMoney;
            return strChineseMoney;
        }

        public static string IntToChineseMoney(Int64 num)
        {
            /// <summary>
            /// 1－9阿拉伯数字的中文大写
            /// </summary>
            string[] BitStrChinese1 = { "", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
            /// <summary>
            /// 进位的中文大写
            /// </summary>
            string[] BitStrChinese2 = { "", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万" };
            num = Math.Abs(num);
            //返回的字符串
            string strChinese = "元";

            if (num > 1000000000)
                return strChinese = "金额超出范围！";
            if (num == 0)
                return strChinese = "零";
            else
            {
                for (int i = 1; num > 0; i++)
                {
                    Int64 l1 = num % 10;
                    int l2 = i - 1;
                    if (l1 == 0)
                        l2 = 0;
                    strChinese = BitStrChinese1[l1] + BitStrChinese2[l2] + strChinese;
                    if (l1 == 0)
                        BitStrChinese2[0] = "";
                    else
                        BitStrChinese2[0] = "零";
                    num = num / 10;
                }
                return strChinese;
            }
        }

        public static string DecInt2Str(string strDecX)
        {
            string strX;
            if (strDecX.EndsWith(".000"))
            {
                try
                {
                    strX = Convert.ToInt32(Convert.ToDecimal(strDecX)).ToString();
                }
                catch
                {
                    strX = strDecX;
                }
            }
            else
                strX = strDecX;
            return strX;
        }

        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns>正确格式：以字母或数字开头，长度在6-17之间，只能包含字符、数字和下划线。 </returns>
        public static bool IsPassword(string input)
        {
            return new Regex(@"^[a-zA-Z1-9]\w{5,17}$").IsMatch(input);
        }

        /// <summary>
        /// 验证邮箱
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsEmail(string input)
        {
            return new Regex(@"^([a-zA-Z0-9]+[_/.-]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_/.-]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$").IsMatch(input);
        }

        /// <summary>        /// Checks the file is textfile or not.        /// </summary>        
        /// <param name="fileName">Name of the file.</param>        /// <returns></returns>        
        public static bool CheckIsTextFile(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            bool isTextFile = true;
            try
            {
                int i = 0; int length = (int)fs.Length;
                byte data;
                while (i < length && isTextFile)
                {
                    data = (byte)fs.ReadByte();
                    isTextFile = (data != 0); i++;
                }
                return isTextFile;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

        const int LCMAP_SIMPLIFIED_CHINESE = 0x02000000;
        const int LCMAP_TRADITIONAL_CHINESE = 0x04000000;

        public enum ConvertType
        {
            Simplified,
            Traditional
        }

        private Encoding gb2312 = Encoding.GetEncoding(936);

        public string SCTCConvert(ConvertType Toc, string strSrcText)
        {
            byte[] source = gb2312.GetBytes(strSrcText);
            byte[] dest = new byte[source.Length];
            switch (Toc)
            {
                case ConvertType.Simplified:
                    {
                        LCMapString(0x0804, LCMAP_SIMPLIFIED_CHINESE, source, -1, dest, source.Length);
                        break;
                    }
                case ConvertType.Traditional:
                    {
                        LCMapString(0x0804, LCMAP_TRADITIONAL_CHINESE, source, -1, dest, source.Length);
                        break;
                    }
            }
            return gb2312.GetString(dest);
        }

        //private void button2_Click(object sender, EventArgs e)
        //{
        //    SCTCConvert(ConvertType.Simplified);
        //}

        //private void button3_Click(object sender, EventArgs e)
        //{
        //    SCTCConvert(ConvertType.Traditional);
        //}

        [DllImport("kernel32.dll", EntryPoint = "LCMapStringA")]
        public static extern int LCMapString(int Locale, int dwMapFlags, byte[] lpSrcStr, int cchSrc, byte[] lpDestStr, int cchDest);

    }


    public class Sorter
    {
        public static void AdjustDataTableRowSeqNum(DataTable dt, string strKeyFieldNme, string strSeqNumFieldNme)
        {
            AdjustDataTableRowSeqNum(dt, strKeyFieldNme, strSeqNumFieldNme, "");
        }

        /// <summary>
        /// 分组字段如：D_NME ASC,F_CDE DESC
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="strKeyFieldNme"></param>
        /// <param name="strSeqNumFieldNme"></param>
        /// <param name="strGroupFields">分组字段如：D_NME ASC,F_CDE DESC</param>
        public static void AdjustDataTableRowSeqNum(DataTable dt, string strKeyFieldNme, string strSeqNumFieldNme,string strGroupFields)
        {
            DataView dvSortNew = dt.DefaultView;
            dvSortNew.RowFilter = "";
            if (strGroupFields != string.Empty)
            {
                dvSortNew.Sort = strGroupFields+","+strSeqNumFieldNme + " ASC";
            }
            else
            {
                dvSortNew.Sort = strSeqNumFieldNme + " ASC";
            }
            DataTable dtSortNew = dvSortNew.ToTable();
            string strGrouptem1 = "";
            string[] strarrGroupftem1 = strGroupFields.Split(',');
            int iSeqNum = 0;
            for (int i = 0; i < dtSortNew.Rows.Count; i++)
            {
                string strGrouptem2 = "";
                if (strGroupFields != string.Empty)
                {
                    for (int k = 0; k < strarrGroupftem1.Length; k++)
                    {
                        if (strarrGroupftem1[k] != string.Empty && strarrGroupftem1[k].Split(' ')[0] != string.Empty)
                        {
                            strGrouptem2 += "," + dtSortNew.Rows[i][strarrGroupftem1[k].Split(' ')[0]].ToString();
                        }
                    }
                }
                if (strGrouptem2 != strGrouptem1)
                {
                    iSeqNum = 0;
                    strGrouptem1 = strGrouptem2;
                }

                if (iSeqNum.ToString() == dtSortNew.Rows[i][strSeqNumFieldNme].ToString())
                {
                    iSeqNum = iSeqNum + 1;
                    continue;
                }
                else
                {
                    DataRow[] arrRowtem1 = dt.Select(strKeyFieldNme + "='" + dtSortNew.Rows[i][strKeyFieldNme].ToString() + "'");
                    if (arrRowtem1.Length > 0)
                    {
                        arrRowtem1[0][strSeqNumFieldNme] = iSeqNum.ToString();
                    }
                }
                iSeqNum = iSeqNum + 1;
            }
        }

        /// <summary>   
        /// 对datatable进行排序，返回排序后的datatable   
        /// </summary>   
        /// <param name="dt">要排序的datatable</param>   
        /// <param name="order">排序字段</param>   
        /// <param name="asc">是否升序</param>   
        /// <returns></returns>   
        static DataTable SortDataTable(DataTable dt, string strSort)   
        {   
            DataView view = dt.DefaultView;
            view.Sort = strSort;// string.Format("{0} {1}", order, (asc ? "asc" : "desc"));   
            return view.ToTable();   
            /*  
            DataRow[] rows = dt.Select("", order + " " + (asc ? "asc" : "desc"));  
            DataTable dt2 = dt.Clone();  
            foreach (DataRow row in rows)  
                dt2.Rows.Add(row.ItemArray);  
            dt.Clear();  
            return dt2;  
            */  
        }

        public static void SortSrcDataTable(DataTable dt, string strSort)
        {
            //排序
            DataSet ds = dt.DataSet;
            string strRelSave = "";
            for (int i = 0; i < ds.Relations.Count; i++)
            {
                string strStem1 = "";
                strStem1 += ds.Relations[i].RelationName;
                strStem1 += "," + ds.Relations[i].ParentTable.TableName;
                string strColstem1 = "";
                for (int r = 0; r < ds.Relations[i].ParentColumns.Length; r++)
                {
                    if (strColstem1 != string.Empty)
                    {
                        strColstem1 += "|";
                    }
                    strColstem1 += ds.Relations[i].ParentColumns[r].ColumnName;
                }
                strStem1 += "," + strColstem1;


                strStem1 += "," + ds.Relations[i].ChildTable.TableName;
                strColstem1 = "";
                for (int r = 0; r < ds.Relations[i].ChildColumns.Length; r++)
                {
                    if (strColstem1 != string.Empty)
                    {
                        strColstem1 += "|";
                    }
                    strColstem1 += ds.Relations[i].ChildColumns[r].ColumnName;
                }
                strStem1 += "," + strColstem1;
                strStem1 += "," + ds.Relations[i].Nested.ToString();

                strRelSave += strRelSave == string.Empty ? strStem1 : ";" + strStem1;

                DataTable dt1 = ds.Relations[i].ParentTable;
                DataTable dt2 = ds.Relations[i].ChildTable;
                string ConstraintName1 = ds.Relations[i].ParentKeyConstraint.ConstraintName;
                string ConstraintName2 = ds.Relations[i].ChildKeyConstraint.ConstraintName;
                ds.Relations.Remove(ds.Relations[i]);
                dt2.Constraints.Remove(ConstraintName2);
                dt1.Constraints.Remove(ConstraintName1);
            }
            DataView dvSortNew = dt.DefaultView;
            dvSortNew.RowFilter = "";
            dvSortNew.Sort = strSort;
            DataTable dtSortNew = dvSortNew.ToTable();
            ds.Tables.Remove(dt);
            ds.Tables.Add(dtSortNew);
            string[] arrRel1 = strRelSave.Split(';');
            for (int i = 0; i < arrRel1.Length; i++)
            {
                string strRelNme = "";
                string strRelMTNme = "";
                string[] strRelMTFNme = new string[0];
                string strRelCTNme = "";
                string[] strRelCTFNme = new string[0];
                bool blNesttem1=false;

                string[] arrReltem2 = arrRel1[i].Split(',');
                for (int r = 0; r < arrReltem2.Length; r++)
                {
                    string strtem2 = arrReltem2[r];
                    if (strtem2.Trim() == string.Empty)
                    {
                        continue;
                    }

                    if (r == 0)
                    {
                        strRelNme = strtem2;
                    }
                    else if (r == 1)
                    {
                        strRelMTNme = strtem2;
                    }
                    else if (r == 2)
                    {
                        strRelMTFNme = strtem2.Split('|');
                    }
                    else if (r == 3)
                    {
                        strRelCTNme = strtem2;
                    }
                    else if (r == 4)
                    {
                        strRelCTFNme = strtem2.Split('|');
                    }
                    else if (r == 5)
                    {
                        blNesttem1 = strtem2=="True";
                    }
                }
                if (strRelNme != string.Empty
                    && strRelMTNme != string.Empty
                    && strRelMTFNme.Length > 0
                    && strRelCTNme != string.Empty
                    && strRelCTFNme.Length > 0)
                {
                    DataColumn[] arrCol1 = new DataColumn[strRelMTFNme.Length];
                    for (int j = 0; j < strRelMTFNme.Length; j++)
                    {
                        arrCol1[j] = ds.Tables[strRelMTNme].Columns[strRelMTFNme[j]];
                    }
                    DataColumn[] arrCol2 = new DataColumn[strRelCTFNme.Length];
                    for (int j = 0; j < strRelCTFNme.Length; j++)
                    {
                        arrCol2[j] = ds.Tables[strRelCTNme].Columns[strRelCTFNme[j]];
                    }


                    ds.Relations.Add(new DataRelation(strRelNme, arrCol1, arrCol2));
                }
            }

        }

        /// <summary>   
        /// 对实体类进行排序   
        /// </summary>   
        /// <typeparam name="T">实体类型，如：User</typeparam>   
        /// <param name="list">实体类的数组</param>   
        /// <param name="order">排序字段（必须为属性）</param>   
        /// <param name="asc">是否按正序排序</param>   
        public static void Sort<T>(object[] list, string order, bool asc)   
        {   
            Type type = typeof(T);   
            PropertyInfo[] pros = type.GetProperties();   
            PropertyInfo pro = pros[0];   
            order = order.ToLower();   
            for (int i = 0; i < pros.Length; i++)   
            {   
                if (pros[i].Name.ToLower().Equals(order))   
                {   
                    pro = pros[i];   
                    break;   
                }   
            }   
            object obj;   
            int j, k = 1;   
            bool done = false;   
            int len = list.Length;   
            while (k < len && !done)   
            {   
                done = true;   
                for (j = 0; j < len - k; j++)   
                {   
                    int b = pro.GetValue(list[j], null).ToString().CompareTo(pro.GetValue(list[j + 1], null).ToString());   
                    if ((asc && b > 0) || (!asc && b < 0))   
                    {   
                        done = false;   
                        obj = list[j];   
                        list[j] = list[j + 1];   
                        list[j + 1] = obj;   
                    }   
                }   
                k++;   
            }   
        }   
//本文来自: IT知道网(http://www.itwis.com) 详细出处参考：http://www.itwis.com/html/net/c/20100517/8336_2.html











        /// <summary>
        /// 冒泡排序法1
        /// </summary>
        /// <param name="list"></param> 

        public static int[] BubbleSort(int[] list)
        {
            for (int i = 0; i < list.Length; i++)
            {
                for (int j = i; j < list.Length; j++)
                {
                    if (list[i] < list[j])
                    {
                        int temp = list[i];
                        list[i] = list[j];
                        list[j] = temp;
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 插入排序法
        /// </summary>
        /// <param name="list"></param>
        public static int[] InsertionSort(int[] list)
        {
            for (int i = 1; i < list.Length; i++)
            {
                int t = list[i];
                int j = i;
                while ((j > 0) && (list[j - 1] > t))
                {
                    list[j] = list[j - 1];
                    --j;
                }
                list[j] = t;
            }
            return list;
        }

        //// <summary>
        /// 选择排序法
        /// </summary>
        /// <param name="list"></param>
        public static int[] SelectionSort(int[] list)
        {
            int min;
            for (int i = 0; i < list.Length - 1; i++)
            {
                min = i;
                for (int j = i + 1; j < list.Length; j++)
                {
                    if (list[j] < list[min])
                        min = j;
                }
                int t = list[min];
                list[min] = list[i];
                list[i] = t;
            }
            return list;
        }

        //// <summary>
        /// 希尔排序法
        /// </summary>
        /// <param name="list"></param>
        public static int[] ShellSort(int[] list)
        {
            int inc;
            for (inc = 1; inc <= list.Length / 9; inc = 3 * inc + 1) ;
            for (; inc > 0; inc /= 3)
            {
                for (int i = inc + 1; i <= list.Length; i += inc)
                {
                    int t = list[i - 1];
                    int j = i;
                    while ((j > inc) && (list[j - inc - 1] > t))
                    {
                        list[j - 1] = list[j - inc - 1];
                        j -= inc;
                    }
                    list[j - 1] = t;
                }
            }
            return list;
        }

        private static void Swap(ref int l, ref int r)
        {
            int s;
            s = l;
            l = r;
            r = s;
        }
        ///<summary>
        /// 快速排序法
        /// </summary>
        /// <param name="list"></param>
        /// <param name="low"></param>
        /// <param name="high"></param>
        public static void Sort(int[] list, int low, int high)
        {
            int pivot;
            int l, r;
            int mid;
            if (high <= low)
                return;
            else if (high == low + 1)
            {
                if (list[low] > list[high])
                    Swap(ref list[low], ref list[high]);
                return;
            }
            mid = (low + high) >> 1;
            pivot = list[mid];
            Swap(ref list[low], ref list[mid]);
            l = low + 1;
            r = high;
            do
            {
                while (l <= r && list[l] < pivot)
                    l++;
                while (list[r] >= pivot)
                    r--;
                if (l < r)
                    Swap(ref list[l], ref list[r]);
            } while (l < r);
            list[low] = list[r];
            list[r] = pivot;
            if (low + 1 < r)
                Sort(list, low, r - 1);
            if (r + 1 < high)
                Sort(list, r + 1, high);
        }






        /// <summary>        /// Checks the file is textfile or not.        /// </summary>        
        /// <param name="fileName">Name of the file.</param>        /// <returns></returns>        
        public static bool CheckIsTextFile(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            bool isTextFile = true;
            try
            {
                int i = 0; int length = (int)fs.Length;
                byte data;
                while (i < length && isTextFile)
                {
                    data = (byte)fs.ReadByte();
                    isTextFile = (data != 0); i++;
                }
                return isTextFile;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

        const int LCMAP_SIMPLIFIED_CHINESE = 0x02000000;
        const int LCMAP_TRADITIONAL_CHINESE = 0x04000000;

        public enum ConvertType
        {
            Simplified,
            Traditional
        }

        private Encoding gb2312 = Encoding.GetEncoding(936);

        public string SCTCConvert(ConvertType Toc, string strSrcText)
        {
            byte[] source = gb2312.GetBytes(strSrcText);
            byte[] dest = new byte[source.Length];
            switch (Toc)
            {
                case ConvertType.Simplified:
                    {
                        LCMapString(0x0804, LCMAP_SIMPLIFIED_CHINESE, source, -1, dest, source.Length);
                        break;
                    }
                case ConvertType.Traditional:
                    {
                        LCMapString(0x0804, LCMAP_TRADITIONAL_CHINESE, source, -1, dest, source.Length);
                        break;
                    }
            }
            return gb2312.GetString(dest);
        }

        //private void button2_Click(object sender, EventArgs e)
        //{
        //    SCTCConvert(ConvertType.Simplified);
        //}

        //private void button3_Click(object sender, EventArgs e)
        //{
        //    SCTCConvert(ConvertType.Traditional);
        //}

        [DllImport("kernel32.dll", EntryPoint = "LCMapStringA")]
        public static extern int LCMapString(int Locale, int dwMapFlags, byte[] lpSrcStr, int cchSrc, byte[] lpDestStr, int cchDest);

    }





}
